package com.common;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import com.common.base.activity.ActivityManager;
import com.common.logger.AndroidLogAdapter;
import com.common.logger.FormatStrategy;
import com.common.logger.Logger;
import com.common.logger.PrettyFormatStrategy;
import com.common.utils.preferences.Prefs;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.Iconics;
import com.okgo.OkGo;
import com.okgo.cache.CacheEntity;
import com.okgo.cache.CacheMode;
import com.okgo.cookie.CookieJarImpl;
import com.okgo.cookie.store.DBCookieStore;
import com.okgo.https.HttpsUtils;
import com.okgo.interceptor.HttpLoggingInterceptor;
import com.okgo.model.HttpHeaders;
import com.okgo.model.HttpParams;
import com.orhanobut.hawk.Hawk;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;

public class CommonApplication extends Application {

    public List<Activity> activities = new ArrayList<Activity>();
    private ActivityManager appActivityManager;
    public static Looper mainLooper;//循环队列
    public static Handler handler;//主线程Handler
    public static Thread mainThread;//主线程
    public static long mainThreadId;//主线程id
    public static CommonApplication instance;
    public static CommonApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appActivityManager = ActivityManager.getActivityManager();
        instance = this;
        //对全局属性赋值
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();
        handler = new Handler();
        Fresco.initialize(this);
        registerFontIcons();
        initialiseStorage();
        /**
         *日志打印初始化
         */
        //Initialize初始化
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(2)         // (Optional) How many method line to show. Default 2
                .methodOffset(3)        // (Optional) Skips some method invokes in stack trace. Default 5
//        .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("Reader")   // (Optional) Custom tag for each log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        //todo
        Logger.d("message");
        Logger.w("no thread info and only 1 method");
        Logger.i("no thread info and method info");
        Logger.e("Custom tag for only one use");//错误信息 红色的
        Logger.json("{ \"key\": 3, \"value\": something}");
        Logger.d(Arrays.asList("foo", "bar"));
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        map.put("key1", "value2");
        Logger.d(map);
        //全局设置默认的 Header
        /*SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //开始设置全局的基本参数（这里设置的属性只跟下面的MaterialHeader绑定，其他Header不会生效，能覆盖DefaultRefreshInitializer的属性和Xml设置的属性）
                layout.setEnableHeaderTranslationContent(false);
                return new MaterialHeader(context).setColorSchemeResources(R.color.colorPrimary,R.color.colorPrimary,R.color.colorPrimary);
            }
        });*/
       /* SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setEnableHeaderTranslationContent(false);
                return null;
            }
        });*/
        OkGo.getInstance().init(this);
        /*initOkGo();*/
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    public ActivityManager getAppActivityManager() {
        return appActivityManager;
    }

    /**
     * 新建了一个activity
     * @param activity
     */
    public void addActivity(Activity activity){
        if(activities!=null && !activities.contains(activity)){
            activities.add(activity);
        }
    }

    /**
     *  结束指定的Activity
     * @param activity-
     */
    public void finishActivity(Activity activity){
        if (activity!=null) {
            this.activities.remove(activity);
            activity.finish();
        }
    }

    /**
     *  结束指定的Activity
     */
    public void finishAllActivitys(){
        for(Activity a : activities) {
            if (a!=null) {
                a.finish();
            }
        }
    }

    /**
     * 应用退出，结束所有的activity
     */
    public void exitClient(){
        for(Activity activity : activities) {
            if (activity!=null) {
                activity.finish();
            }
        }
        System.exit(0);
    }

    /**
     * 重启当前应用
     */
    public static void restart() {
        Intent intent = getInstance().getPackageManager().getLaunchIntentForPackage(getInstance().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        getInstance().startActivity(intent);
    }

    public static Thread getMainThread() {
        return mainThread;
    }

    public static void setMainThread(Thread mMainThread) {
        CommonApplication.mainThread = mMainThread;
    }

    public static long getMainThreadId() {
        return mainThreadId;
    }

    public static void setMainThreadId(long mMainThreadId) {
        CommonApplication.mainThreadId = mMainThreadId;
    }

    public static Looper getMainThreadLooper() {
        return mainLooper;
    }

    public static void setMainThreadLooper(Looper mainLooper) {
        CommonApplication.mainLooper = mainLooper;
    }

    public static Handler getMainHandler() {
        return handler;
    }

    public static void setMainHandler(Handler handler) {
        CommonApplication.handler = handler;
    }

    private void initOkGo() {
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
        headers.put("commonHeaderKey2", "commonHeaderValue2");
        HttpParams params = new HttpParams();
        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
        params.put("commonParamsKey2", "这里支持中文参数");
        //----------------------------------------------------------------------------------------//

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //第三方的开源库，使用通知显示当前请求的log，不过在做文件下载的时候，这个库好像有问题，对文件判断不准确
        //builder.addInterceptor(new ChuckInterceptor(this));

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失

        //https相关设置，以下几种方案根据需要自己设置
        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
        //方法二：自定义信任规则，校验服务端证书
        HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
        //方法三：使用预埋证书，校验服务端证书（自签名证书）
        //HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
        //方法四：使用bks证书和密码管理客户端证书（双向认证），使用预埋证书，校验服务端证书（自签名证书）
        //HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
        //配置https的域名匹配规则，详细看demo的初始化介绍，不需要就不要加入，使用不当会导致https握手失败
        builder.hostnameVerifier(new SafeHostnameVerifier());

        // 其他统一的配置
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3)                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers)                      //全局公共头
                .addCommonParams(params);                       //全局公共参数
    }

    /**
     * 认证规则
     */
    private class SafeTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                for (X509Certificate certificate : chain) {
                    //检查证书是否过期，签名是否通过等
                    certificate.checkValidity();
                }
            } catch (Exception e) {
                throw new CertificateException(e);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    /**
     * 认证规则
     */
    private class SafeHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            //验证主机名是否匹配 具体参考自己实际项目
            return true;
        }
    }

    private void registerFontIcons() {
        Iconics.registerFont(new GoogleMaterial());
        Iconics.registerFont(new CommunityMaterial());
        Iconics.registerFont(new FontAwesome());
    }

    private void initialiseStorage() {
        Prefs.init(this);
        //Hawk 是一个非常便捷的数据库,操作数据库只需一行代码,能存任何数据类型.
        Hawk.init(this).build();
    }
}
